using System;
using MonoTouch.UIKit;
using GameOfLifeX.Core;
using System.Threading.Tasks;
using System.Diagnostics;

namespace GameOfLifeX.IOS.Client
{
	public class MyViewController : UIViewController
	{
		private int _width;
		private int _height;
		private Model _model;

		public MyViewController (int width, int height) 
		{
			_width = width;
			_height = height;
			InitializeModelAndStartTimer ();
		}

		public override void LoadView ()
		{
			base.LoadView ();
			View = new MyView (_width, _height);
		}

		private void InitializeModelAndStartTimer()
		{
			_model = new Model (_width, _height);
			_model.SeedRandomly ();
			StartTimer ();
		}

		async void StartTimer ()
		{
			while (true) {
				await Task.Delay (10);
				GameLoopTick ();
			}
		}

		int loopCounter = 0;
		readonly Stopwatch sw = Stopwatch.StartNew ();
		const int measureFrequency = 20;

		void GameLoopTick ()
		{
			loopCounter++;
			if (loopCounter % measureFrequency == 0)
			{
				Console.WriteLine ("FPS: " + measureFrequency / sw.Elapsed.TotalSeconds);
				sw.Restart ();
			}

			var lastTopuch = ((MyView)View).LastTouch;
			if (lastTopuch != null)
			{
				((MyView)View).LastTouch = null;
				var location = lastTopuch.LocationInView (View);
				var bounds = View.Bounds;
				_model.GenerateCellsAtTouchLocation (bounds.Width, bounds.Height, location.X, location.Y);
			}

			_model.RunGeneration ();
			((MyView)View).RenderCells (_model.GetGrid ());
		}
	}
}

